package com.exp.security.web;

import cn.hutool.core.util.RandomUtil;
import com.exp.security.vo.R;
import com.exp.security.vo.SmsCaptchaVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangxj
 * @date 2025/1/7
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 过期时长
     */
    private static final Integer SMS_EXPIRE_TIME = 5;
    /**
     * 短信验证码前缀- redis key前缀
     */
    private static final String SMS_PREFIX = "sms:phone:";

    @GetMapping("/code")
    public R<SmsCaptchaVO> sms(@RequestParam String phone) {
        // 获取手机号
        log.info("手机号：{}", phone);
        // 2. 模拟调用短信平台获取验证码，以手机号为 key，验证码为 value 存入 redis，过期时间 5 分钟
        String oldCode = stringRedisTemplate.opsForValue().get(SMS_PREFIX + phone);
        if (StringUtils.isNotBlank(oldCode)) {
            return R.fail("请勿频繁发送短信请求");
        }

        String code = RandomUtil.randomNumbers(6);

        stringRedisTemplate.opsForValue().set(SMS_PREFIX + phone, code, SMS_EXPIRE_TIME, TimeUnit.MINUTES);
        log.info("手机号：{} 生成验证码：{}", phone, code);
        // 3. 返回过期时间，方便前端提示多长时间内有效
        SmsCaptchaVO smsCaptchaVO = new SmsCaptchaVO();
        smsCaptchaVO.setPhone(phone);
        smsCaptchaVO.setExpire(SMS_EXPIRE_TIME);
        return R.data(smsCaptchaVO, "短信发送成功");
    }
}
